#include "ImageHandle.h"
#include "HikCamera.h"
#include "Server.h"
#include "base64.h"
#include "process.h"
#include <iostream>
#include <json/json.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include "Robot.h"
#include "log.h"
#include "initialization.h"
#include "ParamProcessing.h"
#include "Processtree.h"
#include "ServerSocket.h"

std::string GetExecutablePath();
const std::string executablePath = GetExecutablePath();

std::string GetExecutablePath()
{
  std::string filePath(__FILE__); // 获取当前源文件的完整路径

  // 找到最后一个路径分隔符
  size_t lastSlash = filePath.find_last_of("/\\");

  // 提取路径
  if (lastSlash != std::string::npos)
  {
    return filePath.substr(0, lastSlash);
  }

  return "";
}

void test()
{
  cv::Mat img = cv::imread("/mnt/e/My_Study/OpenCV/Inexbot_Vision/images/template1.jpg");
  cv::Mat img1 = cv::imread("/mnt/e/My_Study/OpenCV/Inexbot_Vision/images/template2.jpg");
  DetectionResult result = ImageHandle().PatternRecognition(img, img1);
  cv::imwrite(executablePath + "/images/qqrents7.jpg", result.img);
  while (true)
  {
  }
}

int main(int argc, char **argv)
{

  // 系统初始化
  if (!SystemInitialization())
  {
    return -1;
  }

  // test();

  // 等待打开相机
  logMessage("Waiting to turn on the camera!");
  while (!CameraRun(camera))
  {
  }

  // 与上位机TCP通信
  ServerSocket UpperComputerSocket(Upper_Computer_Port);
  if (!UpperComputerSocket.start())
  {
    std::cerr << "Failed to start server." << std::endl;
    return -1;
  }

  if (!UpperComputerSocket.acceptClient())
  {
    std::cerr << "Failed to start server." << std::endl;
    return -1;
  }

  Upper_Computer_fd = UpperComputerSocket.getClientSocket();

  std::thread aaaa(std::bind(&UpperComputerProcessing, std::ref(UpperComputerSocket)));

  if (aaaa.joinable())
  {
    aaaa.join();
  }

  // // 创建子进程，与机器人控制器TCP通信
  // pthread_t tid_r;
  // pthread_create(&tid_r, NULL, Socket7000, NULL);
  // pthread_detach(tid_r);

  // // 创建子进程，与示教器TCP通信
  // pthread_t tid_t;
  // pthread_create(&tid_t, NULL, SocketServer_TeachingDevice, NULL);
  // pthread_detach(tid_t);

  // // 与上位机TCP通信
  // Socket10000();

  // 关闭相机
  camera.StopGrabbing();
  camera.CloseCamera();

  return 0;
}
